package com.qys.livesMall.shop.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qys.livesMall.common.utils.bean.BeanProUtils;
import com.qys.livesMall.framework.view.Paging;
import com.qys.livesMall.framework.view.QysPage;
import com.qys.livesMall.shop.dao.H2ShopBaseDao;
import com.qys.livesMall.shop.mapper.ShopReturnApprovedMapper;
import com.qys.livesMall.shop.modal.dto.ShopReturnSearch;
import com.qys.livesMall.shop.modal.entity.H2ShopBase;
import com.qys.livesMall.shop.modal.entity.ReturnPurchaseDetails;
import com.qys.livesMall.shop.modal.entity.ShopReturnApproved;
import com.qys.livesMall.shop.service.ShopReturnApprovedService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author gmx
 * @since 2023-06-15
 */
@Service
public class ShopReturnApprovedServiceImpl extends ServiceImpl<ShopReturnApprovedMapper, ShopReturnApproved> implements ShopReturnApprovedService {
    @Resource
    ShopReturnApprovedMapper mapper;

    @Autowired
    private H2ShopBaseDao shopBaseDao;


    @Override
    public QysPage<ReturnPurchaseDetails> search(ShopReturnSearch search) {
        List<H2ShopBase> shops=null;
        if (StringUtils.isNotBlank(search.getShopName())) {
            shops = shopBaseDao.getByShopName(search.getShopName());
            if (CollectionUtils.isEmpty(shops)){
                return QysPage.build(search);
            }
            List<Long> shopIds = shops.stream().map(H2ShopBase::getId).collect(Collectors.toList());
            search.setShopIds(shopIds);
        }
        Paging<ShopReturnApproved> page=mapper.search(new Paging<>(search));
        if (CollectionUtils.isEmpty(page.getRecords())){
            return QysPage.build(search);
        }
        if (CollectionUtils.isEmpty(shops)){
            List<Long> shopIds = page.getRecords().stream().map(ShopReturnApproved::getShopId).collect(Collectors.toList());
            shops = shopBaseDao.listByIds(shopIds);
        }

        Map<Long, H2ShopBase> shopBaseMap = shops.stream().collect(Collectors.toMap(H2ShopBase::getId, v -> v));
        List<ReturnPurchaseDetails> vos=new ArrayList<>();
        page.getRecords().forEach(e->{
            ReturnPurchaseDetails vo= BeanProUtils.copyProperties(e,ReturnPurchaseDetails::new);
            H2ShopBase h2ShopBase=shopBaseMap.get(e.getShopId());
            if (null != h2ShopBase){
                vo.setShopName(h2ShopBase.getShopName());
            }
            vos.add(vo);
        });
        return QysPage.build(search).setRecords(vos).setTotal(page.getTotal());
    }

}
